package com.example.distortionmeter.ui.components

import android.Manifest
import android.bluetooth.BluetoothDevice
import android.content.Context
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.example.distortionmeter.viewmodel.DistortionViewModel



// BluetoothDeviceDialog.kt
@Composable
fun BluetoothDeviceDialog(
    viewModel: DistortionViewModel,
    onDismiss: () -> Unit
) {
    val context = LocalContext.current
    val devices by viewModel.bluetoothDevices.collectAsState()
    val isScanning by viewModel.isScanning.collectAsState()
    val isDialogOpen by viewModel.isDialogOpen.collectAsState()
    // 时间状态收集
    val lastScanTimestamp by viewModel.lastScanTimestamp.collectAsState()
    val lastScanTime by viewModel.lastScanTime.collectAsState()
    // 对话框显示时自动开始扫描
    LaunchedEffect(Unit) {
        if (isDialogOpen) {
            val currentTime = System.currentTimeMillis()
            // 60秒间隔检查（60 * 1000 = 60000）
            if (currentTime - lastScanTimestamp > 60000) {
                viewModel.startScan()
            }
        }
    }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("蓝牙设备") },
        text = {
            Column {
                // 扫描状态提示
                if (isScanning) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        CircularProgressIndicator(modifier = Modifier.size(24.dp))
                        Spacer(Modifier.width(8.dp))
                        Text("正在搜索设备...")
                    }
                }

                // 设备列表
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(max = 400.dp), // 限制最大高度
                    contentPadding = PaddingValues(vertical = 8.dp)
                ) {
                    item {
                        Text(
                            text = "最后扫描时间：$lastScanTime",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.outline,
                            modifier = Modifier.padding(8.dp)
                        )
                    }
                    if (devices.isEmpty()) {
                        item {
                            Text(
                                text = if (isScanning) "搜索中..." else "未找到设备",
                                modifier = Modifier.padding(16.dp)
                            )
                        }
                    }
                    items(
                        items = devices,
                        key = { it.address } // 添加唯一key
                    ) { device ->
                        DeviceItem(device, viewModel)
                    }
                }
            }
        },
        confirmButton = {
            Button(onClick = {
                viewModel.startScan() // 此处会触发权限检查和请求
            }) {
                Text("重新搜索")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("关闭")
            }
        }
    )
}

@Composable
private fun DeviceItem(
    device: BluetoothDevice, viewModel: DistortionViewModel,
    context: Context = LocalContext.current) {
    val isConnected by viewModel.isConnected.collectAsState()
    ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH)
    ListItem(
        headlineContent = { Text(device.name ?: "未知设备") },
        supportingContent = { Text(device.address) },
        trailingContent = {
            if (isConnected?.address == device.address) {
                Icon(Icons.Default.Check, "已连接")
            }
        },
        modifier = Modifier.clickable {
            if (isConnected?.address == device.address) {
                // 已连接时点击断开
                viewModel.disconnectDevice()
            } else {
                // 未连接时点击连接
                viewModel.connectToDevice(device)
            }
        }
    )
}
